'''
Created on May 25, 2012

@author: thomas_dao
'''

from web.base import BaseHandler
from web import urls
import logging
from app.query import event_async, invite_async, rating_async, ticket_async, user_event_list_async
from google.appengine.ext import ndb


def get_popularity(count_invite, 
                   count_user_watch, 
                   count_ticket_sold, 
                   rating, 
                   count_rating):
    logging.info(count_invite)
    logging.info(count_user_watch)
    logging.info(count_ticket_sold)
    logging.info(rating)
    logging.info(count_rating)
    
    popularity = count_invite + count_user_watch + count_ticket_sold + \
                 rating + count_rating
    return popularity


class EventPopularityHandler(BaseHandler):
    @ndb.synctasklet
    def get(self):
        # Retrieve all Events currently happening
        # probabbly use projection queries to limit memory
        current_events, past_events = yield (event_async.get_current_events(), 
                                             event_async.get_past_month_events())
        events = current_events + past_events
        event_key_list = []
        for event in events:
            event_key_list.append(event.key)
            
        logging.info(events)
                    
        # Retrieve all required params async
        (count_invite_list,
         count_user_watch_list,
         count_ticket_sold_list,
         rating_list,
         count_rating_list) = yield (invite_async.count_by_event_list(event_key_list),
                                     user_event_list_async.count_by_event_list(event_key_list),
                                     ticket_async.count_by_event_list(event_key_list),
                                     rating_async.rating_by_event_list(event_key_list),
                                     rating_async.count_by_event_list(event_key_list))
        
        # Calculate popularity
        for i in xrange(0, len(events)):
            event = events[i]
            count_invite = count_invite_list[i]
            count_user_watch = count_user_watch_list[i]
            count_ticket_sold = count_ticket_sold_list[i]
            rating = rating_list[i]
            count_rating = count_rating_list[i]
            event.popularity = get_popularity(count_invite, 
                                              count_user_watch, 
                                              count_ticket_sold, 
                                              rating, 
                                              count_rating)
            
        # TODO: Save Events in batches
        ndb.put_multi(events)
        
        self.response.write("Done")
    
    
app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()
